import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/bill_provider.dart';
import '../models/bill.dart';
import '../core/app_theme.dart';

import '../screens/bill/add_edit_bill_screen.dart'; // 添加导入
import '../screens/bill/bill_detail_screen.dart';   // 添加导入


class BillGroupList extends StatelessWidget {
  const BillGroupList({super.key});

  @override
  Widget build(BuildContext context) {
    final billProvider = Provider.of<BillProvider>(context);
    final groupedBills = billProvider.groupedBills;
    final expansionStates = billProvider.expansionStates;

    if (groupedBills.isEmpty) {
      return const Center(
        child: Text(
          '暂无账单数据',
          style: AppTheme.bodyLarge,
        ),
      );
    }

    // 按年月倒序排序
    final sortedYearMonths = groupedBills.keys.toList()
      ..sort((a, b) => b.compareTo(a));

    return ListView.builder(
      itemCount: sortedYearMonths.length,
      itemBuilder: (context, yearMonthIndex) {
        final yearMonth = sortedYearMonths[yearMonthIndex];
        final dateGroups = groupedBills[yearMonth]!;
        
        // 按日期倒序排序
        final sortedDates = dateGroups.keys.toList()
          ..sort((a, b) => b.compareTo(a));

        return _buildYearMonthGroup(
          context,
          yearMonth,
          dateGroups,
          sortedDates,
          expansionStates[yearMonth] ?? false,
        );
      },
    );
  }

  Widget _buildYearMonthGroup(
  BuildContext context,
  String yearMonth,
  Map<String, List<Bill>> dateGroups,
  List<String> sortedDates,
  bool isExpanded,
) {
  final billProvider = Provider.of<BillProvider>(context, listen: false);
  final totalAmount = _calculateMonthTotal(dateGroups);
  final billCount = _calculateMonthBillCount(dateGroups);

  return Card(
    margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
    child: ExpansionTile(
      key: Key(yearMonth),
      leading: const Icon(Icons.folder, color: Colors.brown, size: 24), // 月份用棕色文件夹图标
      title: Text(
        _formatYearMonth(yearMonth),
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: Text(
        '$billCount个账单 • 总计: ¥${totalAmount.toStringAsFixed(2)}',
        style: const TextStyle(fontSize: 12),
      ),
      trailing: Icon(
        isExpanded ? Icons.expand_less : Icons.expand_more,
        color: Colors.grey,
      ),
      initiallyExpanded: isExpanded,
      onExpansionChanged: (expanded) {
        billProvider.toggleExpansion(yearMonth);
      },
      children: sortedDates.map((date) {
        return _buildDateGroup(context, date, dateGroups[date]!);
      }).toList(),
    ),
  );
}
 
  Widget _buildDateGroup(BuildContext context, String date, List<Bill> bills) {
  final totalAmount = _calculateDayTotal(bills);
  
  return Container(
    margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
    decoration: BoxDecoration(
      color: Colors.grey[50],
      borderRadius: BorderRadius.circular(8),
      border: Border.all(color: Colors.grey[300]!),
    ),
    child: ExpansionTile(
      key: Key(date),
      leading: const Icon(Icons.description, color: Colors.teal, size: 20), // 日期用青色文档图标
      title: Text(
        _formatFullDate(date),
        style: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
        ),
      ),
      subtitle: Text(
        '${bills.length}个账单 • ¥${totalAmount.toStringAsFixed(2)}',
        style: const TextStyle(fontSize: 11),
      ),
      trailing: const Icon(Icons.arrow_drop_down, size: 20),
      children: bills.map((bill) => _buildBillItem(context, bill)).toList(),
    ),
  );
}

  Widget _buildBillItem(BuildContext context, Bill bill) {
  return Container(
    margin: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(6),
      border: Border.all(color: Colors.grey[300]!),
    ),
    child: ListTile(
      contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
      minLeadingWidth: 0,
      leading: Container(
        width: 20,
        height: 20,
        decoration: BoxDecoration(
          color: _getStatusColor(bill.status).withOpacity(0.1),
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: _getStatusColor(bill.status)),
        ),
        child: Icon(
          _getStatusIcon(bill.status),
          color: _getStatusColor(bill.status),
          size: 10,
        ),
      ),
      title: Text(
        bill.restaurantName,
        style: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        '${_getStatusText(bill.status)} • ¥${bill.totalAmount.toStringAsFixed(2)}',
        style: TextStyle(
          fontSize: 11,
          color: _getStatusColor(bill.status),
        ),
      ),
      trailing: PopupMenuButton<String>(
        icon: const Icon(Icons.more_vert, size: 16),
        padding: EdgeInsets.zero,
        constraints: const BoxConstraints(
          minWidth: 120,
        ),
        onSelected: (value) => _handlePopupAction(context, bill, value),
        itemBuilder: (BuildContext context) => [
          const PopupMenuItem(
            value: 'detail',
            child: Row(
              children: [
                Icon(Icons.info_outline, size: 16),
                SizedBox(width: 8),
                Text('详情'),
              ],
            ),
          ),
          if (bill.status == 'pending')
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit, size: 16),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
          const PopupMenuItem(
            value: 'delete',
            child: Row(
              children: [
                Icon(Icons.delete, size: 16, color: Colors.red),
                SizedBox(width: 8),
                Text('删除', style: TextStyle(color: Colors.red)),
              ],
            ),
          ),
        ],
      ),
      onTap: () => _viewBillDetail(context, bill),
      onLongPress: () => _showDeleteDialog(context, bill),
    ),
  );
}

void _handlePopupAction(BuildContext context, Bill bill, String action) {
  switch (action) {
    case 'detail':
      _viewBillDetail(context, bill);
      break;
    case 'edit':
      _editBill(context, bill);
      break;
    case 'delete':
      _showDeleteDialog(context, bill);
      break;
  }
}
  // 辅助方法
  double _calculateMonthTotal(Map<String, List<Bill>> dateGroups) {
    double total = 0;
    for (var bills in dateGroups.values) {
      total += _calculateDayTotal(bills);
    }
    return total;
  }

  int _calculateMonthBillCount(Map<String, List<Bill>> dateGroups) {
    int count = 0;
    for (var bills in dateGroups.values) {
      count += bills.length;
    }
    return count;
  }

  double _calculateDayTotal(List<Bill> bills) {
    return bills.fold(0.0, (sum, bill) => sum + bill.totalAmount);
  }

  String _formatYearMonth(String yearMonth) {
    final parts = yearMonth.split('-');
    if (parts.length == 2) {
      return '${parts[0]}年${int.parse(parts[1])}月';
    }
    return yearMonth;
  }

  String _formatFullDate(String fullDate) {
    final parts = fullDate.split('-');
    if (parts.length == 3) {
      return '${parts[0]}年${int.parse(parts[1])}月${int.parse(parts[2])}日';
    }
    return fullDate;
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'completed':
        return Colors.green;
      case 'cancelled':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'pending':
        return '未完成';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知';
    }
  }

  IconData _getStatusIcon(String status) {
    switch (status) {
      case 'pending':
        return Icons.pending;
      case 'completed':
        return Icons.check_circle;
      case 'cancelled':
        return Icons.cancel;
      default:
        return Icons.help;
    }
  }

  void _editBill(BuildContext context, Bill bill) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AddEditBillScreen(billId: bill.id!),
      ),
    ).then((result) {
      if (result == true) {
        final billProvider = Provider.of<BillProvider>(context, listen: false);
        billProvider.loadBills(status: billProvider.currentFilter); // 修改这行
      }
    });
  }

  void _viewBillDetail(BuildContext context, Bill bill) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BillDetailScreen(billId: bill.id!),
      ),
    );
  }

  void _showDeleteDialog(BuildContext context, Bill bill) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除"${bill.restaurantName}"的账单吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(ctx).pop();
              await _deleteBill(context, bill);
            },
            child: const Text(
              '删除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteBill(BuildContext context, Bill bill) async {
    try {
      final billProvider = Provider.of<BillProvider>(context, listen: false);
      await billProvider.deleteBill(bill.id!);
      
      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('账单删除成功'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('删除失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}